package cn.edu.ntu.yyl.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Component
@Aspect
public class LogAspect {
	
	private final Logger logger = LoggerFactory.getLogger(this.getClass());

	@Pointcut("execution(* cn.edu.ntu.yyl.controller.*.*(..))")
	public void log() {
		System.err.println("loglog");
	}
	
	@Before("log()")
	public void doBefore(JoinPoint joinPoint)
	{
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		HttpServletRequest request = attributes.getRequest();
		//获取用户请求的URL
		String url = request.getRequestURL().toString();
		//获取用户ip
		String ip = request.getRemoteAddr();
		//获取类和方法名
		String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
		//请求的参数
		Object[] args = joinPoint.getArgs();
		//构造对象
		RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
		logger.info("Request : {}", requestLog);
		logger.info("-------------doBefore-----------");
	}
	@After("log()")
	public void doAfter(){
		logger.info("-------------doAfter-----------");
	}
	
	@AfterReturning(returning = "result",pointcut = "log()")
	public void doAfterReturn(Object result) {
		logger.info((String) result);
	}

	private class RequestLog{
		private String url;
		private String ip;
		private String classMethod;
		private Object[] args;

		public RequestLog(String url, String ip, String classMethod, Object[] args) {
			this.url = url;
			this.ip = ip;
			this.classMethod = classMethod;
			this.args = args;
		}

		@Override
		public String toString() {
			return "{" +
					"url='" + url + '\'' +
					", ip='" + ip + '\'' +
					", classMethod='" + classMethod + '\'' +
					", args=" + Arrays.toString(args) +
					'}';
		}
	}
}
